package com.ih.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.ih.pojo.Account;
import com.ih.pojo.History;
import com.ih.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class AccountController {
    @Autowired
    private AccountService service;

    /**
     * 登录接口
     * @param userName
     * @param userPwd
     * @param model
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(String userName, String userPwd, Model model, HttpSession session){
        Boolean login = service.login(userName, userPwd);
        if (login){
            session.setAttribute("currentUser",userName);
            //跳转到主页
            return "waterMainnenu";
        }else {
            model.addAttribute("msg","用户名或密码错误！");
            return "index";
        }
    }

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/hello")
    public String hello(){
        return "waterMainnenu";
    }

    @RequestMapping("/pwd")
    public String pwd(){
        return "modifypwd";
    }

    @RequestMapping("/pwdUser")
    public String pwdUser(String userPwd,String newPwd,Model model,HttpSession session){
        String userName = (String) session.getAttribute("currentUser");
        Boolean login = service.login(userName, userPwd);
        if (login){
            Account account = new Account();
            account.setUserName(userName);
            String md5Hex = DigestUtil.md5Hex(newPwd);
            account.setUserPwd(md5Hex);
            boolean b = service.pwdUser(account);
            if (b){
                session.removeAttribute("currentUser");
                return "index";//密码修改成功，跳转到登录页面
            }else {
                model.addAttribute("loginFail","修改密码失败");
                model.addAttribute("currentUser",userName);
                return "modifypwd";
            }
        }else {
            model.addAttribute("loginFail","修改密码失败");
            return "modifypwd";
        }

    }
}
